// pages/guessSong/guessSong.js
import Util from "../../utils/util"
import api from '../../utils/api'
import moment from '../../utils/moment'
var app = getApp();
var appGlobal = getApp();
var token = wx.getStorageSync('token');
var theAnswerNum = 0;
var theUserAnswer = [];
var theKey = 0;
var theNum = 0;
var isEmptyTipsMiddle = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    src: '',
    isClose: 0,
    isHasText: 1,
    array: [1, 1, 1, 1, 1, 1],
    isOnShow: 0,
    userCode: null,
    shareUserId: null,
    getAmount: 0,
    rechargeList: [],
    defualtShareAward: 0,
    answerContent: '',
    successOk: 0,
    // advInfo: [], //广告按钮
    errorMsg: "",
    answerAwardAmount: 0,
    imgSrc:'',
    showUserTitle:''
  },
  //提示
  tipsBtn: function () {
    var _this = this;
    //检查是否存在已输入的空数据
    if (theUserAnswer.length > 0) {
      //临时key索引  
      for (var i = 0; i < theUserAnswer.length; i++) {
        if (theUserAnswer[i] == '' || theUserAnswer[i] == null) {
          theKey = i;
          break;

        }
      }
    }
    api.post('index.php?g=User&m=Consumer&a=tips', {
      type: app.setConfig.type,
      token: token,
      gname_id: theNum,
      key: theKey
    }, (data) => {
      if (data.code == 2000) {
        var theTips = data.data.word;

        for (var i = 0; i < theUserAnswer.length; i++) {
          if (theUserAnswer[i] == null || theUserAnswer[i] == '') {
            theUserAnswer[i] = theTips;
            theKey = i;
            break;
          }
        }
        var amount = _this.data.amount;
        amount = amount - data.data.amount;
        var isAnswerEmpty = _this.checkAnserEmpty();
        if (isAnswerEmpty == false) {
          var answer = '';
          for (var i = 0; i < theUserAnswer.length; i++) {
            answer += theUserAnswer[i];
          }
          var params = {
            type: app.setConfig.type,
            token: token,
            gname_id: _this.data.songNum,
            answer: answer
          };
          _this.setData({
            showUserTitle:answer
          });
          api.post('index.php?g=Api&m=GameCenter&a=checkGame', params, function (res) {
            if (res.code != 2000) {
              _this.setData({
                errorMsg: res.msg
              });
              _this.errorLogBox.showDialog();

            } else {
              //console.log(res);
              var newUsers = res.data.users;
              var newGames = res.data.info;
              //theNum = newGames.
              theNum = newGames.idiom_num;
              theAnswerNum = newGames.answer_num;
              wx.setNavigationBarTitle({
                title: newUsers.level_name//页面标题为路由参数
              });
              _this.setData({
                songNum: theNum,
                amount: newUsers.amount
              });
              var thePath = newGames.answer_image_uri;
              // _this.audioCtx = wx.createAudioContext('myAudio');
              // _this.audioCtx.setSrc(app.setConfig.url + thePath);
              //_this.on();
              var theAnswerBtn = [];
              theUserAnswer = [];
              for (var i = 0; i < theAnswerNum; i++) {
                theAnswerBtn.push(i);
                theUserAnswer[i] = "";
              }

              //thekey = 0;
              _this.setData({
                lyric: newGames.answer_alternative,
                answerBtn: theAnswerBtn,
                moveWith: theAnswerNum * 77 + 65,
                userAnswer: [],
                successOk: 1,
                answerContent: res.data.answerContent,
                answerAwardAmount: res.data.answerAwardAmount,
                imgSrc: app.setConfig.url + thePath
              });
              theKey = 0;
              return;
            };
          });
        }
        this.setData({
          userAnswer: theUserAnswer,
          amount: amount
        });
      } else {
        /*wx.showToast({
          title: data.msg,
          icon: 'loading',
          duration: 2000
        });*/
        _this.setData({
          errorMsg: '金币不够哦'
        });
        _this.errorLogBox.showDialog();
      }
    }, false);

    // _this.initSongInfo();
  },
  emptyBtn: function (e) {
    var theIndex = e.currentTarget.dataset.index;
    console.log(theIndex + 1);
  },
  closeRechareBox: function () {
    this.setData({
      isClose: 0
    });
  },
  //获取充值列表
  showBuyCard: function () {
    // console.log(1);
    this.setData({
      isClose: 1
    });
    var _this = this;
    api.post('index.php?g=User&m=Consumer&a=getAmountsList', {
      type: app.setConfig.type,
      token: token,
      page: 1
    }, (data) => {
      console.log(data);
      if (data.code == 2000) {
        _this.setData({
          rechargeList: data.data
        });
        this.setData({
          isClose: 1
        });
      }
    }, false);
  },
  close: function () {
    this.setData({
      isClose: 0
    });
  },
  on: function () {
    this.setData({
      isOnShow: 1,
      isRoate: 1
    });
   // this.audioCtx.play()
  },
  off: function () {
    this.audioCtx.pause();
    this.setData({
      isOnShow: 0,
      isRoate: 0
    });
  },
  hasLyric: function (e) {
    var _this = this;
    var theNameSmall = e.currentTarget.dataset.name;

    //console.log("执行的是我么")
    //初始变量用于检测是否存在删除字段
    for (var i = 0; i < theUserAnswer.length; i++) {
      if (theUserAnswer[i] == '') {
        theUserAnswer[i] = theNameSmall;
        break;
      }
    }
    var isEmptyAnswer = _this.checkAnserEmpty();
    if (isEmptyAnswer == false) {
      var answer = '';
      for (var i = 0; i < theUserAnswer.length; i++) {
        answer += theUserAnswer[i];
      }
      var params = {
        type: app.setConfig.type,
        token: token,
        gname_id: _this.data.songNum,
        answer: answer
      }
      _this.setData({
        showUserTitle: answer
      });
      var isEmptyCheck = _this.checkAnserEmpty();
      if (isEmptyCheck == false) {
        api.post('index.php?g=Api&m=GameCenter&a=checkGame', params, function (res) {
          if (res.code != 2000) {
            /*wx.showLoading({
              title: res.msg,
              duration: 2000
            })*/
            _this.setData({
              errorMsg: res.msg
            });
            _this.errorLogBox.showDialog();
          } else {
            var thePath = res.data.info.answer_image_uri;
            _this.setData({
              answerContent: res.data.answerContent,
              successOk: 1,
              imgSrc: app.setConfig.url + thePath
            });
            //console.log(res);
            var newUsers = res.data.users;
            var newGames = res.data.info;
            //theNum = newGames.
            theNum = newGames.idiom_num;
            theAnswerNum = newGames.answer_num;
            wx.setNavigationBarTitle({
              title: newUsers.level_name//页面标题为路由参数
            });
            _this.setData({
              songNum: theNum,
              amount: newUsers.amount
            });
          
            // _this.audioCtx = wx.createAudioContext('myAudio');
            // _this.audioCtx.setSrc(app.setConfig.url + thePath);

            var theAnswerBtn = [];
            theUserAnswer = [];
            for (var i = 0; i < theAnswerNum; i++) {
              theAnswerBtn.push(i);
              theUserAnswer[i] = '';
            }
            _this.setData({
              lyric: newGames.answer_alternative,
              answerBtn: theAnswerBtn,
              moveWith: theAnswerNum * 77 + 65,
              userAnswer: [],
              answerAwardAmount: res.data.answerAwardAmount,

            });
            return;
          }
        }, false);
      }

    }
    this.setData({
      isHasText: 0,
      userAnswer: theUserAnswer
    });
  },
  refreshBtn: function () {
    theUserAnswer = [];
    for (var i = 0; i < theAnswerNum; i++) {

      theUserAnswer[i] = '';
    }
    this.setData({
      userAnswer: theUserAnswer
    });
  },
  initSongInfo: function () {
    var _this = this;
    app.post('index.php?g=User&m=Consumer&a=getUserInfo', {
      type: app.setConfig.type,
      token: token
    }, (data) => {
      if (data.code == 2000) {

        theNum = data.data.idiom_num;
        wx.setNavigationBarTitle({
          title: data.data.level_name//页面标题为路由参数
        })
        _this.setData({
          songNum: theNum,
          amount: data.data.amount,
          defualtShareAward: appGlobal.globalData.defaultConfigs.share_award_amount,
        });
        api.post('index.php?g=Api&m=GameCenter&a=getUserGame', {
          type: app.setConfig.type,
          token: token,
          num: theNum
        }, (data) => {
          if (data.code == 2000) {
            // 控制音乐播放
             var thePath = data.data.answer_image_uri;
            //console.log('http://192.168.199.129' + thePath);
            // this.audioCtx = wx.createAudioContext('myAudio');
            // this.audioCtx.setSrc(app.setConfig.url + thePath);
            //this.audioCtx.play();
            // 显示键盘文字
            theAnswerNum = data.data.answer_num;
            //var theAnswerBtn = new Array(theAnswerNum);
            console.log(theAnswerNum);
            var theAnswerBtn = [];
            for (var i = 0; i < theAnswerNum; i++) {
              theAnswerBtn.push(i);
              theUserAnswer[i] = '';
            }
            console.log("创建的数组");
            console.log(theAnswerBtn);
            console.log("创建的用户答案");
            console.log(theUserAnswer);
            _this.setData({
              lyric: data.data.answer_alternative,
              answerBtn: theAnswerBtn,
              moveWith: theAnswerNum * 77 + 65,
              shareUserId: data.data.user_id,
              imgSrc: app.setConfig.url + thePath
            })
          }
        }, false);
      }
    });
  },
  checkAnserEmpty: function () {
    var isEmpty = false;
    for (var i = 0; i < theUserAnswer.length; i++) {
      if (theUserAnswer[i] == "" || theUserAnswer[i] == null) {
        isEmpty = true;
        break;
      }

    }
    return isEmpty;
  },
  dynamicWidth: function () {
    console.log(theAnswerNum);

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    /*console.log('开始调取数据');
    console.log(app.globalData.defualtShareAward);
    
    console.log(app.globalData.code);
    console.log(app.globalData);
    console.log(app.globalData.token);*/
    this.loop(options);
  },
  loop: function (options) {
    var _this = this;

    var token = wx.getStorageSync("token");
   
    if (token) {
      _this.setData({
        userCode: app.globalData.code,
        
        isRoate: 0
      });
      _this.initSongInfo();
      _this.dynamicWidth();
      _this.share();
      _this.advLoading();
    } else {
      setTimeout(function () { _this.loop(options); }, 100);
    }
  },
  //加载广告
  advLoading: function () {
    var _this = this;
    var token = appGlobal.globalData.token;
    var url = "index.php?g=Api&m=GobalConf&a=getGameAdv";
    api.post(url, { token: token, type: appGlobal.setConfig.type }, function (res) {
       _this.setData({
         advInfo: res.data
       });
    }, false);
  },
  share: function () {
    //要求小程序返回分享目标信息
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  onShareAppMessage: function (res) {
    var _this = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    console.log("分享用户信息");
    console.log(app.globalData.userInfo);
    return {
      title: '我已经闯过了' + theNum + '关，谁来与我一战？',
      path: '/pages/home/home?friendid=' + _this.data.shareUserId,
      success: function (res) {
        // 转发成功
        //onsole.log(res.shareTickets);
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success(res) {
              var iv = res.iv;
              var encryptedData = res.encryptedData;
              wx.login({
                success: function (res) {
                  var code = res.code;
                  if (code) {
                    var shareParams = {
                      game_type: app.setConfig.type,
                      code: code,
                      iv: iv,
                      encryptedData: encryptedData,
                      token: token,
                      share_type: 1
                    }
                    api.post('index.php?g=Api&m=Share&a=groupShare', shareParams, function (res) {
                      _this.closeRechareBox();
                      /*console.log("分享返回的结果");
                      console.log(res);*/
                      if (res.code == 2000) {
                        var amount = _this.data.amount;
                        amount = parseInt(amount) + parseInt(res.amount);
                        amount = parseInt(amount);
                        _this.setData({
                          getAmount: res.amount,
                          amount: amount
                        });
                        _this.dialogShare.showDialog();
                        console.log("分享返回")
                        console.log(res);
                      } else {
                        /*console.log("分享返回")
                        console.log(res);
                        wx.showLoading({
                          title: '分享成功',
                        })*/
                      }
                    }, false);
                  }
                }
              })

            }
          });
        } else {
          //普通好友分享
          var shareParams = {
            game_type: app.setConfig.type,
            token: token,
            share_type: 0
          }
          api.post('index.php?g=Api&m=Share&a=groupShare', shareParams, function (res) {
            _this.closeRechareBox();
            if (res.code == 2000) {
              var amount = _this.data.amount;
              amount = parseInt(amount) + parseInt(res.amount);
              amount = parseInt(amount);
              _this.setData({
                getAmount: res.amount,
                amount: amount
              });
              _this.dialogShare.showDialog();
              console.log(res);
            } else {
              console.log(res);
              wx.showLoading({
                title: '分享成功',
              })
            }
          }, false);
        }
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  //音乐播放自动完毕关闭播放按钮
  onSeekedEvent: function (e) {
    //console.log("我停止了");
    this.setData({
      isOnShow: 0,
      isRoate: 0
    });
  },
  //清楚用户输入文字
  clearWord: function (e) {
    var _this = this;
    var answerIndex = e.target.dataset.anserindex;
    var userAnswer = this.data.userAnswer;
    userAnswer[answerIndex] = '';
    _this.setData({
      userAnswer: userAnswer,
    });
    theUserAnswer = userAnswer;
  },
  onReady: function (e) {
    this.dialogShare = this.selectComponent("#sharedialog");
    this.dialogRecharge = this.selectComponent("#rechargedialog");
    this.errorLogBox = this.selectComponent('#errorLogBox');
  },
  goRecharge: function (e) {
    //充值
    var _this = this;
    var token = appGlobal.globalData.token;
    //console.log("充值所需要的token"+token);
    var url = 'index.php?g=Api&m=Payment&a=goPay';
    wx.showLoading({
      title: '请求中....',
    });
    console.log("获取到的数据");
    console.log(e);
    var amount = e.target.dataset.amount;
    var money = e.target.dataset.money;
    var amount_level_id = e.target.dataset.rechargeid;
    var rechareParams = {
      token: token,
      amount: amount,
      money: money,
      amount_level_id: amount_level_id
    }

    var newAmount = parseInt(_this.data.amount) + parseInt(amount);
    api.post(url, rechareParams, function (res) {
      if (res.code == 2000) {

        var payInfo = res.data;
        wx.requestPayment({
          'timeStamp': payInfo.respay.timeStamp,
          'nonceStr': payInfo.respay.nonceStr,
          'package': payInfo.respay.package,
          'signType': 'MD5',
          'paySign': payInfo.respay.paySign,
          'success': function (res) {
            _this.setData({
              getAmount: amount,
              amount: newAmount
            });
            //关闭支付列表弹层

            _this.dialogRecharge.showDialog();
          },
          fail: function (res) {
            /*wx.showToast({
              title: '支付失败',
              icon: 'loading',
              mask: true,
              duration: 1000
            })*/
            _this.setData({
              errorMsg: '支付失败'
            });
            _this.errorLogBox.showDialog();
          }
        });
      } else {
        console.log(res);
        wx.showToast({
          title: res.data.msg,
          icon: 'loading',
          mask: true,
          duration: 1500
        });
      }
      wx.hideLoading();
    }, false);
  },
  closeSucceBox: function () {
    //关闭成功弹出
    var _this = this;
    _this.setData({
      successOk: 0
    });
    _this.on();
  },
  //广告跳转
  goAdvEvent: function () {
    var _this = this;
     var advInfo = _this.data.advInfo;
    if (advInfo) {
      //检测跳转类型
      if (advInfo.adv_type == 0) {
        //普通网页跳转
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + advInfo.adv_info_url
        })
      } else {
        console.log("我执行了么" + advInfo.app_id);
        //小程序跳转
        wx.navigateToMiniProgram({
          appId: advInfo.app_id.toString(),
          path: advInfo.page.toString,
          extraData: advInfo.sence,
          envVersion: 'release',
          success: function (res) {
            console.log("打开小程序成功");
            console.log(res);
          },
          fail: function (e) {
            console.log("打开小程序失败");
            console.log(e);
          }
        });
      }
    }
  }
})